package com.gqj.meter.controller;

import com.gqj.common.annotation.Log;
import com.gqj.common.constant.BusinessConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.exception.ServiceException;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.StringUtils;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.MdInTask;
import com.gqj.meter.domain.MdInTaskDetails;
import com.gqj.meter.domain.MdOutTask;
import com.gqj.meter.domain.MdOutTaskDetails;
import com.gqj.meter.domain.vo.MdInTaskDetailsVo;
import com.gqj.meter.domain.vo.MdOutTaskDetailsVo;
import com.gqj.meter.mapper.MdOutTaskMapper;
import com.gqj.meter.service.IMdOutTaskDetailsService;
import com.gqj.meter.service.IMdOutTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 出入库明细Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdOutTaskDetails", description = "出库明细")
@RestController
@RequestMapping("/meter/mdOutTaskDetails")
public class MdOutTaskDetailsController extends BaseController {
    @Autowired
    private IMdOutTaskDetailsService mdOutTaskDetailsService;
    @Autowired
    private IMdOutTaskService mdOutTaskService;
    @Autowired
    private MdOutTaskMapper mdOutTaskMapper;

    /**
     * 查询出入库明细列表
     */
    @ApiOperation("查询出库明细列表")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTaskDetails:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdOutTaskDetails mdOutTaskDetails) {
        startPage();
        List<MdOutTaskDetails> list = mdOutTaskDetailsService.selectMdOutTaskDetailsList(mdOutTaskDetails);
        return getDataTable(list);
    }

    @Log(title = "出库单明细导入", businessType = BusinessType.IMPORT)
    @ApiOperation("出库单明细导入")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTaskDetails:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String outTaskNo, Boolean isCoverSupport) throws Exception {

        ExcelUtil<MdOutTaskDetails> util = new ExcelUtil<MdOutTaskDetails>(MdOutTaskDetails.class);
        List<MdOutTaskDetails> outTaskDetailsList = util.importExcel(file.getInputStream());
        if (StringUtils.isEmpty(outTaskDetailsList)) {
            return AjaxResult.error("导入明细数据不能为空！");
        }

        if (StringUtils.isNull(outTaskNo)) {
            return AjaxResult.error("任务编号为空，请联系系统管理员");
        }
        if (StringUtils.isNull(isCoverSupport)) {
            return AjaxResult.error("是否覆盖为空，请联系系统管理员");
        }

        MdOutTask mdOutTask = mdOutTaskMapper.selectMdOutTaskByOutTaskNo(outTaskNo);
        if (StringUtils.isNull(mdOutTask)) {
            return AjaxResult.error("导入'" + outTaskNo + "'任务明细失败，任务编号不存在");
        }
        if (!"0".equals(mdOutTask.getStatusCode())) {
            return AjaxResult.error("任务单据'" + mdOutTask.getOutTaskNo() + "'不是待执行状态，无法导入");
        }

//        int outNumber = mdOutTask.getOutNumber();
//        int importNumber = outTaskDetailsList.size();

        if (isCoverSupport) {
//            if (outNumber < importNumber) {
//                return AjaxResult.error("任务单据'" + mdOutTask.getOutTaskNo() + "'规定数量小于导入数量，无法导入");
//            }
        } else {
            MdOutTaskDetails mdOutTaskDetailsQuery = new MdOutTaskDetails();
            mdOutTaskDetailsQuery.setOutTaskNo(outTaskNo);
//            int detailsNumber = mdOutTaskDetailsService.selectMdOutTaskDetailsCount(mdOutTaskDetailsQuery);
//            int total = importNumber + detailsNumber;
//            if (outNumber < total) {
//                return AjaxResult.error("任务单据'" + mdOutTask.getOutTaskNo() + "'规定数量小于导入数量和已导入数量之和，无法导入");
//            }
        }

        return AjaxResult.success(mdOutTaskDetailsService.importMdOutTaskDetails(outTaskDetailsList, outTaskNo, mdOutTask.getAssetsCategory(), isCoverSupport, mdOutTask));
    }

    /**
     * 导出出入库明细列表
     */
    @PreAuthorize("@ss.hasPermi('meter:mdOutTaskDetails:export')")
    @Log(title = "出库明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdOutTaskDetails mdOutTaskDetails) {
        //根据单号查询单据类型
        List<MdOutTask> listTask = mdOutTaskMapper.selectMdOutTaskList(new MdOutTask(){{setOutTaskNo(
                mdOutTaskDetails.getOutTaskNo());}});
        if(listTask.size() < 0){
            throw new ServiceException("单据不存在");
        }

        List<MdOutTaskDetails> list = mdOutTaskDetailsService.exportMdOutTaskDetailsListExcel(mdOutTaskDetails);
        List<MdOutTaskDetailsVo> listvo = new ArrayList<>();
        int i=0;
        for (MdOutTaskDetails mdOutTaskDetails1 : list) {
            i++;
            MdOutTaskDetailsVo mdOutTaskDetailsVo = new MdOutTaskDetailsVo();
            mdOutTaskDetailsVo.setNum(i);
            mdOutTaskDetailsVo.setTypeCode(mdOutTaskDetails1.getTypeCode());
            mdOutTaskDetailsVo.setRfidNo(mdOutTaskDetails1.getRfidNo());
            mdOutTaskDetailsVo.getRemark();
            listvo.add(mdOutTaskDetailsVo);
        }
        MdOutTaskDetailsVo mdOutTaskDetailsVo = new MdOutTaskDetailsVo();
        mdOutTaskDetailsVo.setNum(null);
        mdOutTaskDetailsVo.setTypeCode("配送单位");
        mdOutTaskDetailsVo.setRfidNo("岩泉供电所");
        mdOutTaskDetailsVo.setRemark("日期："+ DateUtils.getDate().replaceAll("-","."));

        listvo.add(mdOutTaskDetailsVo);

        ExcelUtil<MdOutTaskDetailsVo> util = new ExcelUtil<MdOutTaskDetailsVo>(MdOutTaskDetailsVo.class);
        //查询单据类型
        String taskOrderType =listTask.get(0).getTaskOrderType();
        if (taskOrderType.equals(BusinessConstants.TASK_ORDER_TYPE_RETURN)) {
            util.exportExcel(response, listvo, "入库明细数据","拆回电能表交接清单");
        }else {
            util.exportExcel(response, listvo, "入库明细数据","电能表交接清单");
        }
    }

    @PostMapping("/importTemplate")
    @ApiOperation("下载入库单明细导入模板")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTaskDetails:importTemplate')")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<MdOutTaskDetails> util = new ExcelUtil<MdOutTaskDetails>(MdOutTaskDetails.class);
        util.importTemplateExcel(response, "出库明细导入模板");
    }

    /**
     * 获取出入库明细详细信息
     */
    @ApiOperation("获取出库明细详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTaskDetails:query')")
    @GetMapping(value = "/{outTaskDetailsId}")
    public AjaxResult getInfo(@PathVariable("outTaskDetailsId") Long outTaskDetailsId) {
        return success(mdOutTaskDetailsService.selectMdOutTaskDetailsByOutTaskDetailsId(outTaskDetailsId));
    }

    /**
     * 新增出入库明细
     */
    @ApiOperation("新增出库明细")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTaskDetails:add')")
    @Log(title = "出库明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody List<MdOutTaskDetails> mdOutTaskDetailsList) {
        if (StringUtils.isNull(mdOutTaskDetailsList)) {
            return AjaxResult.error("明细为空，请检查重试！");
        }
        return toAjax(mdOutTaskDetailsService.insertMdOutTaskDetails(mdOutTaskDetailsList));
    }

    /**
     * 修改出入库明细
     */
    @ApiOperation("修改出库明细")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTaskDetails:edit')")
    @Log(title = "出库明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdOutTaskMap mdOutTaskMap) throws IOException, ParserConfigurationException, SAXException {
        Long outTaskId = mdOutTaskMap.getOutTaskId();
        if (null == outTaskId || outTaskId == 0) {
            return AjaxResult.error("任务ID为空，请联系系统管理员！");
        }

        String outTaskNo = mdOutTaskMap.getOutTaskNo();
        if (StringUtils.isNull(outTaskNo)) {
            return AjaxResult.error("任务编号为空，请联系系统管理员！");
        }

        String assetsCategory = mdOutTaskMap.getAssetsCategory();
        if (StringUtils.isNull(assetsCategory)) {
            return AjaxResult.error("资产大类为空，请联系系统管理员！");
        }

        MdOutTask mdOutTask = mdOutTaskService.selectMdOutTaskByOutTaskId(outTaskId);
        if (null == mdOutTask) {
            return AjaxResult.error("任务不存在，请联系系统管理员！");
        }
        if (!outTaskNo.equals(mdOutTask.getOutTaskNo())) {
            return AjaxResult.error("任务编号不匹配，请联系系统管理员！");
        }
        if (!assetsCategory.equals(mdOutTask.getAssetsCategory())) {
            return AjaxResult.error("资产大类不匹配，请联系系统管理员！");
        }
        if (!"1".equals(mdOutTask.getStatusCode())) {
            return AjaxResult.error("任务不是执行中状态，无法修改明细！");
        }

        List<MdOutTaskDetails> mdOutTaskDetailsList = mdOutTaskMap.getMdOutTaskDetailsList();
        if (null == mdOutTaskDetailsList || mdOutTaskDetailsList.size() == 0) {
            return AjaxResult.error("任务明细为空，请联系系统管理员！");
        }
        mdOutTaskMap.setTaskOrderType(mdOutTask.getTaskOrderType());
        mdOutTaskMap.setOperId(mdOutTask.getOperId());
        mdOutTaskMap.setRelaId(mdOutTask.getRelaId());
        return toAjax(mdOutTaskDetailsService.updateMdOutTaskDetails(mdOutTaskMap));
    }

    public static class MdOutTaskMap {
        /**
         * 主键
         */
        private Long outTaskId;

        private String assetsCategory;

        private String outTaskNo;

        private String taskOrderType;

        private Long operId;

        private String useEquipment;

        private Long relaId;

        public Long getRelaId() {
            return relaId;
        }

        public void setRelaId(Long relaId) {
            this.relaId = relaId;
        }

        private List<MdOutTaskDetails> mdOutTaskDetailsList;

        public String getUseEquipment() {
            return useEquipment;
        }

        public void setUseEquipment(String useEquipment) {
            this.useEquipment = useEquipment;
        }

        public Long getOperId() {
            return operId;
        }

        public void setOperId(Long operId) {
            this.operId = operId;
        }

        public String getTaskOrderType() {
            return taskOrderType;
        }

        public void setTaskOrderType(String taskOrderType) {
            this.taskOrderType = taskOrderType;
        }

        public Long getOutTaskId() {
            return outTaskId;
        }

        public void setOutTaskId(Long outTaskId) {
            this.outTaskId = outTaskId;
        }

        public String getAssetsCategory() {
            return assetsCategory;
        }

        public void setAssetsCategory(String assetsCategory) {
            this.assetsCategory = assetsCategory;
        }

        public String getOutTaskNo() {
            return outTaskNo;
        }

        public void setOutTaskNo(String outTaskNo) {
            this.outTaskNo = outTaskNo;
        }

        public List<MdOutTaskDetails> getMdOutTaskDetailsList() {
            return mdOutTaskDetailsList;
        }

        public void setMdOutTaskDetailsList(List<MdOutTaskDetails> mdOutTaskDetailsList) {
            this.mdOutTaskDetailsList = mdOutTaskDetailsList;
        }
    }

    /**
     * 删除出入库明细
     */
    @ApiOperation("删除出库明细")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTaskDetails:remove')")
    @Log(title = "出库明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{outTaskDetailsIds}/{outTaskNo}")
    public AjaxResult remove(@PathVariable Long[] outTaskDetailsIds, @PathVariable String outTaskNo) {
        if (StringUtils.isNull(outTaskNo)) {
            return AjaxResult.error("任务编号为空，请联系系统管理员！");
        }
        MdOutTask mdOutTask = mdOutTaskMapper.selectMdOutTaskByOutTaskNo(outTaskNo);
        if (!"0".equals(mdOutTask.getStatusCode())) {
            return AjaxResult.error("任务已执行，不允许删除明细！");
        }
        return toAjax(mdOutTaskDetailsService.deleteMdOutTaskDetailsByOutTaskDetailsIds(outTaskDetailsIds, mdOutTask.getAssetsCategory()));
    }
}
